package com.ruoyi.system.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.DataSyncConstants;
import com.ruoyi.common.utils.sync.MdmProtocol;
import com.ruoyi.system.domain.DepInfo;
import com.ruoyi.system.domain.EmpDepRelationship;
import com.ruoyi.system.domain.EmpInfo;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 同步组织架构，集成xxl-job
 *
 * @author alex
 */
@Component
public class SysDataService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysDataService.class);
    @Autowired
    private IDepInfoService depInfoService;
    @Autowired
    private IEmpInfoService empInfoService;
    @Autowired
    private IEmpDepRelationshipService empDepRelationshipService;
    @Autowired
    private MdmProtocol mdmProtocol;

    @XxlJob("sysMdmUpdateAncestors")
    public void sysMdmUpdateAncestors() throws Exception {
        XxlJobHelper.log("开始更新组织表上级");
        depInfoService.sysMdmUpdateAncestors();
    }
    /**
     * 处理人员，组织，人员组织关系数据
     * @throws Exception
     */
    @XxlJob("sysMdmPeData")
    public void sysMdmPeData() throws Exception {
        //传入参数，第一个参数表示业务，第二个参数all或者part，同步全部还是部分
        String allParam = XxlJobHelper.getJobParam();
        String[] params = allParam.split(",");
        String iFaceCode = params[0];
        String allOrPart = params[1];
        XxlJobHelper.log("开始同步组织架构[{}]", iFaceCode);
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 23, 00, 00);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        calendar.add(Calendar.DATE, -2);
        String startTime = simpleDateFormat.format(calendar.getTime());
        //传入参数，all表示同步全部,否则只同步最近2天
        if ("all".equalsIgnoreCase(allOrPart)) {
            startTime = "1900-01-01 00:00:00";
        }
        String endTime = "2099-01-01 00:00:00";
        this.sycdata(iFaceCode, startTime, endTime);
    }

    private void sycdata(String iFaceCode, String lastUpdateDate, String currentTime) throws Exception {
        long start = System.currentTimeMillis();
        // 清空临时表
        String requestID = System.currentTimeMillis() + "";
        int pageNumber = 0;
        int totalCount = 0;
        JSONObject json = new JSONObject();
        json.put("requestID", requestID);
        json.put("ifaceCode", iFaceCode);
        json.put("pageNumber", pageNumber);
        JSONObject result = null;
        // 第一次请求
        result = mdmProtocol.getMDMData(json, lastUpdateDate, currentTime);
        totalCount = result.getIntValue("totalCount");
        json.put("batch", result.getString("batch"));
        json.put("batchHistory", result.getString("batchHistory"));
        // 循环从MDM取数，并写入临时表
        for (pageNumber = 0; pageNumber < totalCount; pageNumber++) {
            LOGGER.info("ZZJG第" + pageNumber + "页");
            json.put("pageNumber", pageNumber);
            result = mdmProtocol.getMDMData(json, lastUpdateDate, currentTime);
            if (DataSyncConstants.ZZJG.equals(iFaceCode)) {
                List<DepInfo> list = JSON.parseArray(result.getJSONArray("depInfoList").toJSONString(), DepInfo.class);
                if (list.size() > 0) {
                    depInfoService.insertDepInfoBach(list);
                }
            } else if (DataSyncConstants.RYXX.equals(iFaceCode)) {
                List<EmpInfo> empList = JSON.parseArray(result.getJSONArray("custMasterDataIntfList").toJSONString(), EmpInfo.class);
                if (empList.size() > 0) {
                    empInfoService.insertEmpInfoBatch(empList);
                }
            } else if (DataSyncConstants.RYZZGX.equals(iFaceCode)) {
                List<EmpDepRelationship> empDepList = JSON.parseArray(result.getJSONArray("empDepRelationships").toJSONString(), EmpDepRelationship.class);
                if (empDepList.size() > 0) {
                    empDepRelationshipService.insertEmpDepBatch(empDepList);
                }
            }
        }
        if (DataSyncConstants.RYXX.equals(iFaceCode)) {
            //人员同步后，需要刷新默认角色
            empInfoService.refreshUserRole();
        }
        long end = System.currentTimeMillis();
        LOGGER.info("同步组织架构[{}]表耗时：{}", iFaceCode, (end - start) / 1000);
    }
}
